package com.fa7.android.example.listafacil;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class CompraDB {
	private final static String DB_NAME = "compra_db";
	private final static int DB_VERSION = 1;
	public final static String TABLE_NAME = "compras";
	private final static String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, value DOUBLE NOT NULL, name TEXT NOT NULL, qtd INTEGER NOT NULL, img_filename TEXT)";
	
	private SQLHelper mSqlHelper;
	private Context mContext;
	private SQLiteDatabase mDb;
	
	public CompraDB(Context c) {
		mContext = c;
		mSqlHelper = new SQLHelper(mContext, TABLE_NAME, DB_VERSION, CREATE_TABLE);
		mDb = mSqlHelper.getWritableDatabase();
	}
	
	public long insert(Compra c) {
		ContentValues content = new ContentValues();
		content.put("value",  c.getValue());
		content.put("qtd", c.getQtd());
		content.put("name", c.getName());
		content.put("img_filename", c.getImgFilename());
		
		return mDb.insert(TABLE_NAME, null, content);
	}
	
	public void update(Compra c) {
		ContentValues content = new ContentValues();
		content.put("value",  c.getValue());
		content.put("qtd", c.getQtd());
		content.put("name", c.getName());
		content.put("img_filename", c.getImgFilename());
		mDb.update(TABLE_NAME, content, "_id = ?", new String[] {  c.getId().toString() });
	}
	
	public void delete(Compra c) {
		mDb.delete(TABLE_NAME, "_id = ?", new String[] {  c.getId().toString() });
	}
	
	public Compra query(Integer id) {
		Cursor c = mDb.query(TABLE_NAME, null, "_id = ?", new String[] { id.toString() }, null, null, null);
		
		if (c.moveToFirst()) {
			return new Compra(c);
		}
		
		return null;
	}
	
	public List<Compra> queryAll() {
		Cursor c = mDb.query(TABLE_NAME, null, null, null, null, null, null);
		
		List<Compra> list = new ArrayList<Compra>();
		while (c.moveToNext()) {
			list.add(new Compra(c));
		}
		
		return list;
	}
}